import type { TBody, TMessageRange, TParams } from '@/types';
import { createConfig, getQueryParams, handleReqMiddleware } from '@/lib/api';
import type {
  IClientMessage,
  IMessage,
  IMessageStatistics,
  IPagination,
} from '@/interfaces';

export const queryAllMessage = (
  params?: TParams
): Promise<Response | IPagination<IClientMessage>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/messages?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const serverQueryAllMessage = (
  params?: TParams
): Promise<Response | IPagination<IMessage>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/messages/server?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const queryMessage = (
  params?: TParams
): Promise<Response | IMessage> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/messages/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const queryMessagesByUserId = (
  params?: TParams
): Promise<Response | IPagination<IMessage>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/messages/users/${config.id}?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const queryMessageStatistics = (
  params?: TParams
): Promise<Response | IMessageStatistics> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/messages/statistics', config).then(
    handleReqMiddleware
  );
};

export const markMessageRead = (
  params: TBody<void>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PATCH' });
  return fetch(config.baseURL + `/messages/${config.id}/read`, config).then(
    handleReqMiddleware
  );
};

export const removeMessage = (
  params: TBody<void>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(config.baseURL + `/messages/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const serverRemoveMessage = (
  params: TBody<void>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(config.baseURL + `/messages/server/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const sendMessage = (
  params: TBody<{
    name: string;
    content: string;
    messageRange: TMessageRange;
    businessId?: number;
    businessName?: string;
    businessRemark?: string;
    recipient?: number;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(config.baseURL + `/messages/send`, config).then(
    handleReqMiddleware
  );
};
